package com.romain.risotto.entities;

import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.romain.risotto.manager.GameManager;

public abstract class SpaceSpriteObject extends Sprite  {

	public short getId() {
		return id;
	}

	public void setId(short id) {
		this.id = id;
	}

	protected short id;
	//protected PhysicsHandler physic;
	protected float direction = 0;
	protected boolean isManualUpdated = true;
	protected Body body;
	protected GameManager game;
	
	public SpaceSpriteObject(boolean pisManualUpdated, float pX, float pY,
			ITextureRegion pTextureRegion, VertexBufferObjectManager vbo) {
		super(pX, pY, pTextureRegion, vbo);
		isManualUpdated = pisManualUpdated;

		if (!isManualUpdated) {
			//physic = new PhysicsHandler(this);
			//this.registerUpdateHandler(physic);
		}
		game = GameManager.getInstance();
		
	}
	public void setBody(Body pbody){
		body = pbody;
		this.setUserData(body);
	}
	public Vector2 getSpeed(){
		if(body!=null){
			return body.getLinearVelocity();
		}
		else return null;
	}

	@Override
	protected void onManagedUpdate(final float pSecondsElapsed) {
		if(isManualUpdated)
		{
			return ;
		}
		super.onManagedUpdate(pSecondsElapsed);
		
		
		//Log.d("ship", this.getClass().toString()+" speedX: "+physic.getVelocityX()+ "  - speedY: "+physic.getVelocityY()+ "  accX: "+physic.getAccelerationX()+"  accY:"+physic.getAccelerationY());
	}

	public float getDirection() {
		return direction;
	}

	public void setDirection(float direction) {
		this.direction = direction;
		if(body!=null){
			body.setAngularVelocity(0);
			body.setTransform(body.getPosition(), direction);
		}
	}




	protected void delete() {
		GameManager.getInstance().getEngine().runOnUpdateThread(new Runnable() {
			@Override
			public void run() {
				// Detete objects safely here.
				
				final PhysicsConnector facePhysicsConnector = game.physicWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(SpaceSpriteObject.this);

				game.physicWorld.unregisterPhysicsConnector(facePhysicsConnector);
				game.physicWorld.destroyBody(facePhysicsConnector.getBody());

				SpaceSpriteObject.this.detachSelf();
				
				//System.gc();
				
			}

		});
	}
	protected abstract void createBody();

	
}
